package service

import (
	"context"
	"engine/cache"
	"fmt"
	"github.com/goccy/go-json"
	"io/ioutil"
	"net/http"
	"time"
)

type WxShop struct {
	AppID     string
	AppSecret string
}

// TokenResponse represents the response from WeChat token API
type TokenResponse struct {
	AccessToken string `json:"access_token"`
	ExpiresIn   int    `json:"expires_in"`
	ErrCode     int    `json:"errcode"`
	ErrMsg      string `json:"errmsg"`
}

func (s *WxShop) GetToken() string {
	var ctx = context.Background()
	key := "wxShop:token:key:"
	token, err := cache.RedisContextGet[string](ctx, key)
	if err != nil || token == nil {
		//
		respData, err := s.GetWeChatToken()
		if err != nil {
			return ""
		}
		tokens := respData.AccessToken
		tokenExpiry := time.Duration(respData.ExpiresIn-100) * time.Second
		cache.RedisContextSet(ctx, key, tokens, tokenExpiry)
		return tokens
	}

	return *token
}
func (s *WxShop) GetWeChatToken() (*TokenResponse, error) {
	// Construct the URL
	url := fmt.Sprintf("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s",
		s.AppID, s.AppSecret)

	// Make the GET request
	resp, err := http.Get(url)
	if err != nil {
		return nil, fmt.Errorf("request failed: %v", err)
	}
	defer resp.Body.Close()

	// Read the response body
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, fmt.Errorf("failed to read response: %v", err)
	}

	// Parse the JSON response
	var tokenResp TokenResponse
	if err := json.Unmarshal(body, &tokenResp); err != nil {
		return nil, fmt.Errorf("failed to parse JSON: %v", err)
	}

	// Check for errors in the response
	if tokenResp.ErrCode != 0 {
		return nil, fmt.Errorf("wechat API error: %d - %s",
			tokenResp.ErrCode, tokenResp.ErrMsg)
	}

	return &tokenResp, nil
}
